/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.elect.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.elect.domain.ElectClassify;
import com.fzhucc.modules.elect.domain.dto.ElectQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.elect.repository.ElectClassifyRepository;
import com.fzhucc.modules.elect.domain.dto.ElectClassifyDto;
import com.fzhucc.modules.elect.domain.dto.ElectClassifyQueryCriteria;
import com.fzhucc.modules.elect.service.mapstruct.ElectClassifyMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyg
* @date 2023-12-18
**/
@Service
@RequiredArgsConstructor
public class ElectClassifyService {

    private final ElectClassifyRepository electClassifyRepository;
    private final ElectClassifyMapper electClassifyMapper;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(ElectClassifyQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public Map<String,Object> queryAll(ElectClassifyQueryCriteria criteria, Pageable pageable){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals("福建省")) {
            criteria.setOrgArea(null);
        }
        Page<ElectClassify> page = electClassifyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(electClassifyMapper::toDto));
    }

    public List<ElectClassifyDto> queryAll(ElectClassifyQueryCriteria criteria){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return electClassifyMapper.toDto(electClassifyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    public String orgAreaReturnIfHave(String org) {
        if (org!=null && !org.equals("")){
            return org;
        }else{
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {//未登录则外面传进来
                return "";
            } else {
                Optional<User> userOptional = userRepository.findById(userId);
                User res = userOptional.get();
                return res.getOrgArea();
            }
        }
    }

    @Transactional
    public ElectClassifyDto findById(Integer id) {
        ElectClassify electClassify = electClassifyRepository.findById(id).orElseGet(ElectClassify::new);
        ValidationUtil.isNull(electClassify.getId(),"ElectClassify","id",id);
        return electClassifyMapper.toDto(electClassify);
    }

    @Transactional(rollbackFor = Exception.class)
    public ElectClassifyDto create(ElectClassify resources) {
        resources.setOrgArea(orgAreaReturnIfHave(resources.getOrgArea()));
        return electClassifyMapper.toDto(electClassifyRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ElectClassify resources) {
        ElectClassify electClassify = electClassifyRepository.findById(resources.getId()).orElseGet(ElectClassify::new);
        ValidationUtil.isNull( electClassify.getId(),"ElectClassify","id",resources.getId());
        electClassify.copy(resources);
        electClassify.setOrgArea(orgAreaReturnIfHave(resources.getOrgArea()));
        electClassifyRepository.save(electClassify);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            electClassifyRepository.deleteById(id);
        }
    }

    public void download(List<ElectClassifyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ElectClassifyDto electClassify : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("图标url", electClassify.getImg());
            map.put("推送小程序", electClassify.getIsShow());
            map.put("分类名称", electClassify.getName());
            map.put("排序", electClassify.getSort());
            map.put("区域划分", electClassify.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}